-- OutdoorSceneManager.lua
-- 户外场景管理器：作为室内场景之前的关卡，人物从左侧出生走到右侧切换到室内

local OutdoorSceneManager = {}
OutdoorSceneManager.__index = OutdoorSceneManager

-- 导入必要模块
local Vector2 = require("vector")

function OutdoorSceneManager.new()
    local instance = {
        -- 场景配置
        sceneId = "OutdoorScene",
        displayName = "户外关卡",
        
        -- 背景和地板配置
        backgroundPath = "Image/level-outdoor/level-outdoor-background.png",
        floorPath = "Image/level-outdoor/level-outdoor-floor.png",
        
        -- 场景参数（与室内相同）
        levelWidth = 24000,           -- 逻辑宽度 24000像素
        levelHeight = 8000,           -- 逻辑高度 8000像素
        floorWidth = 2000,            -- 地板贴图宽度
        floorHeight = 160,            -- 地板贴图高度
        
        -- 场景节点
        sceneNode = nil,
        backgroundNode = nil,
        floorLayer = nil,
        
        -- 玩家和场景切换
        playerNode = nil,
        sceneManager = nil,
        isTransitioning = false,
        transitionDistance = 24000,   -- 切换到室内场景的距离
        
        -- 地面参数（与室内相同）
        groundY = 320,                 -- 地面高度
        groundHeight = 50,             -- 地面厚度
        
        -- 相机参数（与室内相同）
        cameraZoom = 1.0,
        
        -- 远景效果参数
        backgroundParallaxFactor = 0.3,  -- 背景移动比例
        
        -- 状态
        isInitialized = false,
        debugMode = true,
        
        -- 地板切片管理
        floorTiles = {},
        activeFloorRange = {start = 0, count = 0},
        
        -- 场景边界（用于碰撞检测）
        sceneBounds = {
            left = 0,
            right = 24000,
            top = 8000,
            bottom = 0,
            width = 24000,
            height = 8000
        },
        
        -- 地面平台（用于碰撞检测）
        groundPlatforms = {}
    }
    
    return setmetatable(instance, OutdoorSceneManager)
end

-- 初始化户外场景
function OutdoorSceneManager:initialize(sceneNode, playerNode, sceneManager)
    print("====================================")
    print("初始化户外关卡场景管理器")
    print("====================================")
    
    if not sceneNode then
        print("错误：场景节点为空")
        return false
    end
    
    self.sceneNode = sceneNode
    self.playerNode = playerNode
    self.sceneManager = sceneManager
    
    -- 创建背景层（远景效果）
    self:createBackgroundLayer()
    
    -- 创建地板层（循环贴图）
    self:createFloorLayer()
    
    -- 创建地面碰撞平台
    self:createGroundPlatforms()
    
    self.isInitialized = true
    
    print("户外关卡场景初始化完成")
    print(string.format("场景尺寸: %d×%d", self.levelWidth, self.levelHeight))
    print(string.format("玩家从左侧出生，走到 x=%d 切换到室内场景", self.transitionDistance))
    
    return true
end

-- 创建背景层（带远景效果）
function OutdoorSceneManager:createBackgroundLayer()
    if not self.sceneNode then return end
    
    local Sprite = require("Sprite")
    local Node = require("Node")
    local Vec2 = require("Vec2")
    local Cache = require("Cache")
    
    -- 创建背景容器
    self.backgroundNode = Node()
    self.backgroundNode.position = Vec2(self.levelWidth / 2, self.levelHeight / 2)
    
    -- 加载背景纹理
    local backgroundTexture = nil
    if Cache:load(self.backgroundPath) then
        local Texture2D = require("Texture2D")
        backgroundTexture = Texture2D(self.backgroundPath)
    end
    
    if backgroundTexture then
        -- 创建背景精灵
        local backgroundSprite = Sprite(backgroundTexture)
        if backgroundSprite then
            -- 缩放背景以覆盖整个场景
            local scaleX = self.levelWidth / backgroundSprite.width
            local scaleY = self.levelHeight / backgroundSprite.height
            backgroundSprite.scaleX = scaleX
            backgroundSprite.scaleY = scaleY
            
            self.backgroundNode:addChild(backgroundSprite)
            
            print(string.format("户外背景加载成功: 原始尺寸(%d×%d), 缩放(%.2f×%.2f)", 
                backgroundSprite.width, backgroundSprite.height, scaleX, scaleY))
        end
    else
        -- 创建备用背景
        self.backgroundNode.size = Vec2(self.levelWidth, self.levelHeight)
        self.backgroundNode.color = {0.2, 0.5, 0.8, 1}  -- 蓝天颜色
        
        -- 添加云朵装饰
        self:createClouds()
        
        print("使用备用户外背景")
    end
    
    -- 添加到场景
    self.sceneNode:addChild(self.backgroundNode, -100)
end

-- 创建云朵装饰（备用背景时使用）
function OutdoorSceneManager:createClouds()
    local Sprite = require("Sprite")
    local Vec2 = require("Vec2")
    
    -- 创建几个云朵
    local cloudPositions = {
        {x = 2000, y = 6000, scale = 2.0},
        {x = 6000, y = 6500, scale = 1.5},
        {x = 12000, y = 5800, scale = 2.5},
        {x = 18000, y = 6200, scale = 1.8},
        {x = 22000, y = 5900, scale = 2.2}
    }
    
    for i, pos in ipairs(cloudPositions) do
        -- 创建简单云朵形状
        local cloud = Node()
        cloud.size = Vec2(400 * pos.scale, 150 * pos.scale)
        cloud.position = Vec2(pos.x, pos.y)
        cloud.color = {1, 1, 1, 0.8}  -- 白色半透明
        
        self.backgroundNode:addChild(cloud)
    end
end

-- 创建地板层（循环使用2000像素宽的地板贴图）
function OutdoorSceneManager:createFloorLayer()
    if not self.sceneNode then return end
    
    local Sprite = require("Sprite")
    local Node = require("Node")
    local Vec2 = require("Vec2")
    local Cache = require("Cache")
    
    -- 创建地板层容器
    self.floorLayer = Node()
    self.floorLayer.position = Vec2(0, self.groundY)
    
    -- 加载地板纹理
    local floorTexture = nil
    if Cache:load(self.floorPath) then
        local Texture2D = require("Texture2D")
        floorTexture = Texture2D(self.floorPath)
    end
    
    -- 计算需要的地板切片数量
    local tileCount = math.ceil(self.levelWidth / self.floorWidth)
    
    for i = 1, tileCount do
        local tileNode = Node()
        local tileX = (i - 1) * self.floorWidth
        
        if floorTexture then
            -- 创建地板精灵
            local floorSprite = Sprite(floorTexture)
            if floorSprite then
                -- 调整地板大小
                floorSprite.scaleX = 1.0
                floorSprite.scaleY = self.groundHeight / floorSprite.height
                floorSprite.anchor = Vec2(0, 0)  -- 左下角锚点
                tileNode:addChild(floorSprite)
            end
        else
            -- 创建占位地板（渐变绿色）
            tileNode.size = Vec2(self.floorWidth, self.groundHeight)
            local greenValue = 0.3 + (i % 3) * 0.1
            tileNode.color = {0.1, greenValue, 0.2, 1}
        end
        
        tileNode.position = Vec2(tileX, 0)
        self.floorLayer:addChild(tileNode)
        
        table.insert(self.floorTiles, {
            node = tileNode,
            index = i,
            position = tileX
        })
    end
    
    -- 添加到场景
    self.sceneNode:addChild(self.floorLayer, -50)
    
    print(string.format("地板层创建完成: %d 个切片，每个宽度 %d", tileCount, self.floorWidth))
end

-- 创建地面碰撞平台
function OutdoorSceneManager:createGroundPlatforms()
    print("创建户外地面碰撞平台...")
    
    self.groundPlatforms = {}
    
    -- 创建连续的地面平台（整个关卡宽度）
    local groundPlatform = {
        x = 0,
        y = self.groundY,
        width = self.levelWidth,
        height = self.groundHeight,
        isWalkable = true,
        type = "outdoor_ground"
    }
    
    table.insert(self.groundPlatforms, groundPlatform)
    
    print("户外地面碰撞平台创建完成")
end

-- 更新场景（每帧调用）
function OutdoorSceneManager:update(dt, playerX, playerY)
    if not self.isInitialized or not self.playerNode then return end
    
    -- 检查场景切换条件
    self:checkSceneTransition()
    
    -- 更新背景的远景效果
    self:updateBackgroundParallax()
    
    return true
end

-- 更新背景的远景效果
function OutdoorSceneManager:updateBackgroundParallax()
    if not self.backgroundNode or not self.playerNode then return end
    
    local playerX = self.playerNode.x or 0
    
    -- 计算背景应该移动的距离（产生远景效果）
    -- 背景移动速度 = 玩家移动速度 * 视差因子
    local backgroundOffsetX = playerX * self.backgroundParallaxFactor
    
    -- 限制背景移动范围，避免穿帮
    local maxBackgroundOffset = self.levelWidth * 0.1
    backgroundOffsetX = math.max(-maxBackgroundOffset, math.min(backgroundOffsetX, maxBackgroundOffset))
    
    -- 设置背景位置
    self.backgroundNode.x = self.levelWidth / 2 - backgroundOffsetX
end

-- 检查场景切换条件
function OutdoorSceneManager:checkSceneTransition()
    if not self.playerNode or self.isTransitioning then return end
    
    local playerX = self.playerNode.x or 0
    
    -- 当玩家走到场景最右侧时切换到室内场景
    if playerX >= self.transitionDistance - 100 then
        print(string.format("玩家到达场景边界: x=%.1f/%.1f", playerX, self.transitionDistance))
        self:transitionToIndoorScene()
    end
end

-- 切换到室内场景（修复版本）
function OutdoorSceneManager:transitionToIndoorScene()
    if self.isTransitioning then return end
    
    self.isTransitioning = true
    
    print("====================================")
    print("切换到室内场景...")
    print("====================================")
    
    -- 这里触发场景切换
    if self.sceneManager then
        -- 直接切换场景，不使用 scheduleOnce
        if self.sceneManager.switchToScene then
            self.sceneManager:switchToScene("LevelScene", {
                fromDirection = "left",  -- 从左侧进入
                transitionType = "outdoor_to_indoor"
            })
        end
    else
        print("错误：场景管理器不可用")
        self.isTransitioning = false
    end
end

-- 获取玩家起始位置（在场景最左侧出生）
function OutdoorSceneManager:getPlayerStartPosition()
    return {
        x = 100,                    -- 从左侧100像素处出生
        y = self.groundY + 150      -- 在地面之上150像素
    }
end

-- 获取地面平台（用于碰撞检测）
function OutdoorSceneManager:getGroundPlatforms()
    return self.groundPlatforms
end

-- 检查位置是否可行走
function OutdoorSceneManager:isWalkable(x, y, characterRadius)
    characterRadius = characterRadius or 25
    
    for _, platform in ipairs(self.groundPlatforms) do
        -- 检查水平对齐
        if x >= platform.x - characterRadius and x <= platform.x + platform.width + characterRadius then
            local platformTop = platform.y + platform.height
            local characterBottom = y - characterRadius
            
            -- 检查垂直距离
            if characterBottom >= platformTop - 30 and characterBottom <= platformTop + 10 then
                return true
            end
        end
    end
    
    return false
end

-- 获取应站立的地面
function OutdoorSceneManager:getStandingPlatform(x, y, characterRadius)
    characterRadius = characterRadius or 25
    local characterBottom = y - characterRadius
    
    for _, platform in ipairs(self.groundPlatforms) do
        -- 检查水平对齐
        if x >= platform.x - characterRadius and x <= platform.x + platform.width + characterRadius then
            local platformTop = platform.y + platform.height
            
            -- 检查垂直距离
            if characterBottom >= platformTop - 30 and characterBottom <= platformTop + 5 then
                return {
                    type = "outdoor_ground",
                    x = platform.x,
                    y = platformTop,
                    width = platform.width,
                    height = platform.height,
                    isSlope = false
                }
            end
        end
    end
    
    return nil
end

-- 获取场景边界
function OutdoorSceneManager:getSceneBounds()
    return self.sceneBounds
end

-- 清理资源
function OutdoorSceneManager:cleanup()
    print("清理户外关卡资源...")
    
    if self.floorLayer and self.floorLayer.parent then
        self.floorLayer:removeFromParent()
    end
    
    if self.backgroundNode and self.backgroundNode.parent then
        self.backgroundNode:removeFromParent()
    end
    
    self.floorTiles = {}
    self.groundPlatforms = {}
    self.floorLayer = nil
    self.backgroundNode = nil
    self.sceneNode = nil
    self.playerNode = nil
    self.sceneManager = nil
    self.isInitialized = false
    self.isTransitioning = false
    
    print("户外关卡资源清理完成")
end

return OutdoorSceneManager